from rest_framework.permissions import BasePermission  # 权限父类
from django.contrib.auth.models import Group  # auth的组表
from rest_framework.response import Response

# 老师的权限
class TeacherPermission(BasePermission):
    def has_permission(self, request, view):  # 权限定义的方法
        user = request.user  # 用户
        group = Group.objects.filter(name='老师').first()  # 老师组对象
        user_groups = user.groups.all()  # zl [老师]
        return user.is_superuser or group in user_groups

# 判断是否是当前登录用户的权限
class ActiveUserPermission(BasePermission):
    def has_permission(self, request, view):  # 权限定义的方法
        user = request.user
        return user.id == int(view.kwargs['pk'])  # 转整型

# 判断是否是当前登录用户的权限
class ActiveUserPPermission(BasePermission):
    def has_permission(self, request, view):  # 权限定义的方法
        user = request.user
        return user.id == int(request.data.get('user'))  # 转整型


from functools import update_wrapper  # 更改函数属性的辅助函数

# 更改权限的装饰器
def wrap_permission(*permissions,validate_permission=True):
    def decorator(func):
        def wrapper(self,request,*args,**kwargs):
            self.permission_classes = permissions
            if validate_permission:
                self.check_permissions(request)
            return func(self,request,*args,**kwargs)
        return update_wrapper(wrapper,func)
    return decorator


# 装饰器 会把当前登录的用户id添加到装饰函数的请求当中
def auto_user(func):
    def wrapper(self, request, *args, **kwargs):
        request.POST._mutable = True  # 让请求的参数可以被修改
        request.data['user'] = request.user.id  # user = 1
        return func(self,request,*args,**kwargs)
    return wrapper


# 修改的装饰器
def update_auto_user(func):
    def wrapper(self, request, *args, **kwargs):
        # 判断当前的用户是不是这篇文章的创建者
        # 文章 1  作者 3  用户 5
        res = self.get_queryset().filter(id=kwargs['pk'],user=request.user)
        if not res:
            return Response({'detail':'你没有修改的权限'})

        request.POST._mutable = True  # 让请求的参数可以被修改
        request.data['user'] = request.user.id  # user = 1
        return func(self,request,*args,**kwargs)
    return wrapper


# 删除的装饰器
def destroy_auto_user(func):
    def wrapper(self, request, *args, **kwargs):
        # 判断当前的用户是不是这篇文章的创建者
        # 文章 1  作者 3  用户 5
        res = self.get_queryset().filter(id=kwargs['pk'], user=request.user)
        if not res:
            return Response({'detail': '你没有删除的权限'})
        return func(self, request, *args, **kwargs)
    return wrapper


# 管理员权限
class RootPermission(BasePermission):
    def has_permission(self, request, view):  # 权限定义的方法
        user = request.user
        return user.is_superuser  # 1管理员

